package com.tqjc.system.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.enums.GateNameEnum;
import com.tqjc.system.common.enums.GateRecordStatusEnum;
import com.tqjc.system.core.gate.asyn.OpenGateThread;
import com.tqjc.system.core.gate.constants.GateConstant;
import com.tqjc.system.core.gate.service.SysGateService;
import com.tqjc.system.core.threadpool.ScheduledPoolManager;
import com.tqjc.system.core.threadpool.ThreadPoolManager;
import com.tqjc.system.core.util.MyStringUtils;
import com.tqjc.system.core.util.UUIDUtil;
import com.tqjc.system.system.dao.SysGateRecordDao;
import com.tqjc.system.system.entity.SysGateRecordEntity;
import com.tqjc.system.system.model.bo.SysGateRecordBO;
import com.tqjc.system.system.service.SysGateRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 86195
 * @version 1.0
 * @description 道闸服务类
 * @date 2023/9/22 16:05
 */
@Service
@Slf4j
public class SysGateRecordServiceImpl extends ServiceImpl<SysGateRecordDao, SysGateRecordEntity> implements SysGateRecordService {


    @Autowired
    private SysGateService sysGateService;

    private Map<String,OpenGateThread> threadMap = new HashMap<>();

    @Override
    public IPage<SysGateRecordEntity> getListByPage(IPage<SysGateRecordEntity> page,SysGateRecordBO sysGateRecordBO) {

        LambdaQueryWrapper<SysGateRecordEntity> wrapper = new LambdaQueryWrapper<SysGateRecordEntity>()
                .eq(StringUtils.isNotEmpty(sysGateRecordBO.getCarLicense()), SysGateRecordEntity::getCarLicense,sysGateRecordBO.getCarLicense())
                .orderByDesc(SysGateRecordEntity::getUpdateDate);

        return super.page(page,wrapper);
    }

    @Override
    public SysGateRecordEntity queryById(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public SysGateRecordEntity getMaterialByCarlicense(String carLicense) {
        //todo 调用接口获取物料信息
        return null;
    }

    @Override
    public void updateInfo(SysGateRecordBO sysGateRecordBO) throws Exception {
        SysGateRecordEntity sysGateRecord = SysGateRecordEntity.builder().idKey(Long.valueOf(sysGateRecordBO.getIdKey()))
                .carLicense(sysGateRecordBO.getCarLicense()).status(sysGateRecordBO.getStatus())
                .exitTime(sysGateRecordBO.getExitDate()).build();
        int i = baseMapper.updateById(sysGateRecord);
        if(i <= 0){
            throw  new Exception("更新失败");
        }

    }

    @Override
    public String openGate(String gateNameParam,String idKey,String status) throws Exception {
        List<Integer> gateIndexList = GateConstant.GATE_NAME_RELATION_INDEX_MAP.get(gateNameParam);
        OpenGateThread openGateThread = OpenGateThread.builder().sysGateService(sysGateService)
                .gateIndexList(gateIndexList).build();
        ThreadPoolManager.getInstance().execute(openGateThread);
        if(StringUtils.isNotEmpty(idKey)){
            String currStatus;
            if(GateRecordStatusEnum.STATUS_ENTER.getStatus().equals(status)){
                //前面状态为入闸  状态更新为出闸
                currStatus = GateRecordStatusEnum.STATUS_EXIT.getStatus();
            } else {
                //状态更新为入闸
                currStatus = GateRecordStatusEnum.STATUS_ENTER.getStatus();
            }
            //从table过来的道闸请求，还有更新数据
            SysGateRecordBO updateDTO = SysGateRecordBO.builder().idKey(idKey).exitDate(new Date())
                    .status(currStatus).build();
            this.updateInfo(updateDTO);
        } else {
            idKey = UUIDUtil.getUUID();
        }
        threadMap.put(idKey,openGateThread);
        return idKey;
//        for (Integer integer : gateIndexList) {
//            try {
//
//                sysGateService.openGate(integer);
//            } catch (Exception e) {
//                log.error("请求打开道闸异常",e);
//                throw new Exception("请求打开道闸异常");
//            }
//        }
    }

    @Override
    public void stopOpen(String idKey) throws Exception {
        try {

            OpenGateThread thread = threadMap.get(idKey);
            threadMap.remove(idKey);
            thread.closeGate();
        } catch (Exception e){
            log.error("停止打开道闸失败",e);
            throw new Exception("停止打开道闸失败");
        }
    }

    @Override
    public void monitor() {
        sysGateService.monitor();
    }

    @Override
    public void acceptResult(String resJson) {
        try {
            //车牌号码
            int index = 0;
            //车牌最长的理论长度
            String carNo = resJson.substring(0, 10);
            int carNoChineseNum = MyStringUtils.getChineseNum(carNo);
            //车牌实际截取
            carNo = resJson.substring(0, 10 - index - carNoChineseNum).trim();
            index = carNoChineseNum + index;
            //物料编码
            String matCode = resJson.substring(10 - index, 20 - index);
            int matCodeChineseNum = MyStringUtils.getChineseNum(matCode);
            matCode = resJson.substring(10 - index, 20 - index - matCodeChineseNum).trim();
            index = matCodeChineseNum + index;


            //物料名称
            String matName = resJson.substring(20 - index, 40 - index);
            int i = matName.indexOf(" ");
            matName = resJson.substring(20 - index, 20 - index + i + 1);
            int matNameChineseNum = MyStringUtils.getChineseNum(matName);
            matName = resJson.substring(20 - index, 40 - index - matNameChineseNum).trim();
            index = matNameChineseNum + index;

            //卸车地点
            String unloadPos = resJson.substring(40 - index, 50 - index);
            int unloadPosChineseNum = MyStringUtils.getChineseNum(unloadPos);
            index = unloadPosChineseNum + index;
//            unloadPos = resJson.substring(33 - index, 38 - index).trim();
            //毛重

            String grossWgt = resJson.substring(50 - index, 60 - index).trim();
            //上游不带小数点过来，自己处理小数位置   三位小数
            grossWgt = String.valueOf(Double.parseDouble(grossWgt) / 1000);
            //皮重
            String tareWgt = resJson.substring(60 - index, 70 - index).trim();
            //上游不带小数点过来，自己处理小数位置   三位小数
            tareWgt = String.valueOf(Double.parseDouble(tareWgt) / 1000);
            //净重
            String netWgt = resJson.substring(70 - index, 80 -index).trim();
            //上游不带小数点过来，自己处理小数位置   三位小数
            netWgt = String.valueOf(Double.parseDouble(netWgt) / 1000);

            //年
//            int year = Integer.valueOf(resJson.substring(80, 84));
//            //月
//            int month = Integer.valueOf(resJson.substring(84, 86));
//            //日
//            int day = Integer.valueOf(resJson.substring(86, 88));
//            //时
//            int hour = Integer.valueOf(resJson.substring(88, 90));
//            //分
//            int minute = Integer.valueOf(resJson.substring(90, 92));
//            //秒
//            int second = Integer.valueOf(resJson.substring(92, 94));
//            LocalDateTime sendTime = LocalDateTime.of(year, month, day, hour, minute, second);
            String id = resJson.substring(100 - index, 132 - index).trim();
            String gateName = resJson.substring(132 - index).trim();

            SysGateRecordEntity sysGateEntity = SysGateRecordEntity.builder().idKey(Long.parseLong(id))
                    .enterTime(new Date()).status(GateRecordStatusEnum.STATUS_ENTER.getStatus())
                    .materialName(matName).materialNo(matCode).carLicense(carNo)
                    .grossWgt(grossWgt).tareWgt(tareWgt).netWgt(netWgt).build();
            //数据更新
            baseMapper.updateById(sysGateEntity);
            //打开道闸
            List<Integer> gateIndexs = GateConstant.GATE_NAME_RELATION_INDEX_MAP.get(gateName);
            for (Integer gateIndex : gateIndexs) {
                sysGateService.openGate(gateIndex);
            }
        } catch (Exception e){
            log.error("接受TMS系统返回信息异常",e);
        }


    }
}
